package com.gexiaobao.pigeon.ui.fragment.mine.organization

import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import com.flyjingfish.openimagelib.OpenImage
import com.flyjingfish.openimagelib.enums.MediaType
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.model.bean.OrgListResponse
import com.gexiaobao.pigeon.app.model.param.FollowOrgParams
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.FragmentOrgDetailBinding
import com.gexiaobao.pigeon.ui.adapter.MyPagerAdapter
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentAuction
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentNotice
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentOrgIntro
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentOrgMatch
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.google.android.material.appbar.AppBarLayout
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import kotlin.math.abs

/**
 * created by : hxw
 * @date : 20221124
 * Describe : 组织详情
 */
class FragmentOrgDetail : BaseFragment<OrgDetailViewModel, FragmentOrgDetailBinding>(), AppBarLayout.OnOffsetChangedListener {

    private var orgIcon: String = ""
    private var tabTitles = arrayListOf<String>()
    private val fragments = ArrayList<Fragment>()
    lateinit var data: OrgListResponse
    private var mType = 0//1：我加入的，2：我关注的
    private var position = 0

    override fun initView(savedInstanceState: Bundle?) {
        setStatusBarTranslucent()
        /** tabLayout去除点击背景 */
        mDatabind.tabCollect.tabRippleColor = ColorStateList.valueOf(ContextCompat.getColor(requireContext(), android.R.color.transparent))
        mDatabind.viewmodel = mViewModel
        mDatabind.appBar.addOnOffsetChangedListener(this)
        tabTitles = arrayListOf(getString(R.string.Competition), getString(R.string.announcement), getString(R.string.describe))//, getString(R.string.auction)
        mType = requireArguments().getInt("type")
        position = requireArguments().getInt("position")
        data = requireArguments().getParcelable("data")!!
        orgIcon = data.icon
        mViewModel.title.set(data.name)
        mViewModel.memberNum.set(getString(R.string.member) + ": " + data.memberNum)
        mViewModel.followNum.set(getString(R.string.follow) + ": " + data.followNum)
        mViewModel.followStatusStr.set(if (data.followStatus == 1) getString(R.string.cancel_follow) else getString(R.string.follow))
        mViewModel.joinStatusStr.set(if (data.joinStatus == 1) getString(R.string.Already_a_member) else getString(R.string.Not_yet_joined))
        ImageLoaderManager.loadCircleImageFall(context, orgIcon, mDatabind.image, R.mipmap.profilepic_str_1)

        fragments.clear()
        fragments.add(FragmentOrgMatch.newInstance(data.id.toString(), data.joinStatus))
        fragments.add(FragmentNotice.newInstance(data.id.toString(),data.desc))
        fragments.add(FragmentOrgIntro.newInstance(data.desc))
//        fragments.add(FragmentAuction.newInstance())
        mDatabind.viewpage.adapter = activity?.let { MyPagerAdapter(childFragmentManager, it, fragments, tabTitles) }
        mDatabind.viewpage.offscreenPageLimit = 3
        mDatabind.tabCollect.setupWithViewPager(mDatabind.viewpage)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.ivOrgDetailBack,
            mDatabind.ivDetailBack,
            mDatabind.tvOrgDetailCare,
            mDatabind.image,
            mDatabind.orgAssDetailMember
        ) {
            when (it) {
                mDatabind.ivOrgDetailBack -> nav().navigateUp()
                mDatabind.image -> openBigImage()
                mDatabind.ivDetailBack -> nav().navigateUp()
                mDatabind.tvOrgDetailCare -> {
                    val body = FollowOrgParams(
                        orgId = data.id
                    )
                    showLoading(getString(R.string.loading))
                    if (mViewModel.followStatusStr.get() == "取消关注") {
                        mViewModel.cancelFollowing(body)
                    } else {
                        mViewModel.followOrg(body)
                    }
                }
            }
        }
    }

    private fun openBigImage() {
        OpenImage.with(context)
            .setClickImageView(mDatabind.image)
            .setSrcImageViewScaleType(ImageView.ScaleType.CENTER_CROP, true)
            .setImageUrl(orgIcon, MediaType.IMAGE).show()
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.followOrgResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                mViewModel.followStatusStr.set(getString(R.string.cancel_follow))
                mViewModel.searchOrgById(data.id)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }

        mViewModel.cancelFollowOrgResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                mViewModel.followStatusStr.set(getString(R.string.follow))
                mViewModel.searchOrgById(data.id)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        mViewModel.orgInfoResult.observe(viewLifecycleOwner) {
            if (it != null) {
                mViewModel.followNum.set(getString(R.string.cancel_follow) + ": " + it.followNum)
            }
        }
    }

    override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
        val absVerticalOffset = abs(verticalOffset)//AppBarLayout竖直方向偏移距离px
        val totalScrollRange = appBarLayout?.totalScrollRange//AppBarLayout总的距离px

        if (totalScrollRange != null) {
            if (absVerticalOffset <= totalScrollRange * 0.4) {
                mDatabind.orgAssDetailToolbarRl.visibility = View.GONE
                mDatabind.toolbar.isVisible = false
            } else if (absVerticalOffset >= totalScrollRange * 0.7) {
                mDatabind.orgAssDetailToolbarRl.visibility = View.VISIBLE
                mDatabind.toolbar.isVisible = true
            }
        }
    }
}